class CustomersController < ApplicationController
  # GET /customers/new
  def new
    @customer = Customer.new
  end
  
  # TODO: Validations must be added here for non AR objects
  def create
    account = AccountService.new(account_map)
    external_subscription_id = account.create
    
    one_click = OneClickService.new(account_map)
    external_cim_id = one_click.create
               
    @customer = Customer.create(:email_address            => customer_email_address,
                                :phone_number             => "#{params[:customer][:phone_number]}",
                                :interval                 => "#{params[:customer][:interval]}",
                                :external_subscription_id => external_subscription_id,
                                :external_cim_id          => external_cim_id )
                                
    if external_cim_id == -1 or external_subscription_id == -1
      process_create_exception("Failed to upgrade account.")
    else
      flash[:notice] = 'Account was successfully upgraded.'
    end
  end

  private
  
  def process_create_exception(message)
    logger.info(message)
    flash[:error] = message
    render :text => message
  end
  
  def account_map
    {
      :first_name => "#{params[:first_name]}",
      :last_name => "#{params[:last_name]}",
      :email => customer_email_address,
      :phone => "#{params[:customer][:phone_number]}",
      :interval => "#{params[:customer][:interval]}",
      :billing_address => "#{params[:billing_address]}",
      :billing_city =>  "#{params[:billing_city]}",
      :billing_state => "#{params[:billing_state]}",
      :billing_zip => "#{params[:billing_zip]}",
      :shipping_address => "#{params[:shipping_address]}",
      :shipping_city => "#{params[:shipping_city]}",
      :shipping_state => "#{params[:shipping_state]}",
      :shipping_zip => "#{params[:shipping_zip]}",
      :credit_card_number => "#{params[:credit_card_number]}",
      :expiration_month => "#{params[:month]}", 
      :expiration_year => "#{params[:year]}"
    }
  end
end
